package demo4;
@SuppressWarnings({"all"})
class MyBlockingQuene{
    private String[] data=new String[1000];
    private volatile int head=0;
    private volatile int tail=0;
    private volatile int size=0;
    //数据进入队列
    public void put(String elem) throws InterruptedException {
        synchronized (this){
            while(size==data.length){
                this.wait();
            }
            //把这个数据插入到我们的这个队列的最后面
            data[tail]=elem;
            tail++;
            //判断是不是凑了一个环形循环过程，是的话就需要进行这个置零操作
            if(tail==data.length){
                tail=0;
            }
            size++;
            this.notify();
        }
    }
    //数据出队列
    public String take() throws InterruptedException {
        synchronized (this){
            while(size==0){
                this.wait();
            }
            String ret=data[head];
            head++;
            if(head==data.length){
                head=0;
            }
            size--;
            this.notify();
            return ret;
        }
    }
}

public class zuseduilie {
    public static void main(String[] args) {
        MyBlockingQuene quene=new MyBlockingQuene();
        Thread t1=new Thread(()->{
            while(true){
                try {
                    String ret=quene.take();
                    System.out.println("消费元素"+ret);
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }

            }
        });

        //生产者生产元素
        Thread t2=new Thread(()->{
            int num=1;
            while(true){
                try {
                    quene.put(num+"");
                    System.out.println("生产元素"+num);
                    num++;
                    //Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        t1.start();
        t2.start();
    }
}
